use chrono::{Duration, Utc};
use jsonwebtoken::{EncodingKey, Header};
use serde::{Deserialize, Serialize};
use crate::{domain::error::Result};

pub const  JWT_SECRET: &str = "top_secret_key";

#[derive(Debug, Deserialize, Serialize)]
pub struct Claims {
	pub sub: i64,
	pub exp: i64,
	pub iat: i64,
}

impl Claims {
	pub fn new(id: i64) -> Self {
		let iat = Utc::now();
		let exp = iat + Duration::hours(24);

		Self {
			sub: id,
			iat: iat.timestamp(),
			exp: exp.timestamp(),
		}
	}
}

pub fn sign(id: i64) -> Result<String> {
	Ok(jsonwebtoken::encode(
		&Header::default(),
		&Claims::new(id),
		&EncodingKey::from_secret(JWT_SECRET.as_bytes()),
	)?)
}

